package study.datastructure.search;/**
 * @program: datastructure
 * @author: lcy
 * @create: 2024-06-25 22:14
 */

/**
 2024/6/25,
 */

//二分查找
public class BinarySearch {
public  static  int binarySearch(int [] arr,int key){

    int left=0;
    int right=arr.length-1;

    while (left<=right){
        int mid=(left+right)/2;
        if(arr[mid]==key){
            return mid;
        } else if (arr[mid]<key) {
            left=mid+1;
        }else {
            right=mid-1;
        }
    }
    return -1; //未找到元素
}

    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 9, 11};
        int key = 7;
        int result = binarySearch(arr, key);
        System.out.println("Element found at index: " + result);
    }

}
